#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>

#define Data int
#define INIT 2

typedef struct List
{
	Data* arr;
	int size;
	int capacity;
}List;

void Test1(List *ps);
void Init(List* ps);
void  List_PushBack(List* ps, int num);
void List_PopBack(List* ps);
void List_Print(List* ps);
void List_Destroy(List* ps);
void List_PushFront(List* ps, int num);
void List_PopFront(List* ps);
void List_Insert(List* ps, int pos, int num);
void List_Erase(List* ps, int pos);

int main()
{
	
	List s;
	Init(&s);
	Test1(&s);


	List_Destroy(&s);

	return 0;
}

void Test1(List* ps)
{
	List_PushBack(ps, 1);
	List_PushBack(ps, 2);
	List_PushBack(ps, 3);
	List_PushBack(ps, 4);
	List_PushBack(ps, 5);
	List_PushBack(ps, 6);
	List_Print(ps);
	putchar('\n');

	List_PopBack(ps);
	List_PopBack(ps);
	List_PopBack(ps);
	List_Print(ps);
	putchar('\n');

	List_PushFront(ps, 10);
	List_PushFront(ps, 20);
	List_Print(ps);
	putchar('\n');

	List_PopFront(ps);
	List_Print(ps);
	putchar('\n');

	List_Insert(ps, 2, 66);
	List_Erase(ps, 3);
	List_Print(ps);
}

void Init(List *ps)
{
	ps->arr = (Data*)malloc(sizeof(Data) * INIT);
	if (ps->arr == NULL)
	{
		perror("malloc");
		exit(-1);
	}
	ps->capacity = INIT;
	ps->size = 0;
}

void Check_Capacity(List *ps)
{
	if (ps->capacity == ps->size)
	{
		Data* temp = (Data*)realloc(ps->arr,ps->capacity * 2 * sizeof(Data));
		if (temp == NULL)
		{
			perror("realloc");
			exit(-1);
		}	
		ps->arr = temp;
		ps->capacity *= 2;
	}
}

void  List_PushBack(List* ps, int num)
{
	
	Check_Capacity(ps);
	ps->arr[ps->size++] = num;

}

void List_PushFront(List* ps, int num)
{
	
	Check_Capacity(ps);
	for (int i = ps->size; i > 0; i--)
	{
		ps->arr[i] = ps->arr[i - 1];
	}
	ps->arr[0] = num;
	ps->size++;
}

void List_PopFront(List* ps)
{
	for (int i = 0; i < ps->size; i++)
	{
		ps->arr[i] = ps->arr[i + 1];
	}
	if (ps->size > 0)
	{
		ps->size--;
	}
}

void List_PopBack(List* ps)
{
	if (ps->size > 0)
	{
		ps->size--;
	}
}

void List_Insert(List* ps, int pos, int num)
{
	Check_Capacity(ps);
	for (int i = ps->size; i > pos - 1; i--)
	{
		ps->arr[i] = ps->arr[i - 1];
	}
	ps->arr[pos - 1] = num;
	ps->size++;
}

void List_Erase(List* ps, int pos)
{
	for (int i = pos - 1; i < ps->size; i++)
	{
		ps->arr[i] = ps->arr[i + 1];
	}
	if (ps->size > 0)
	{
		ps->size--;
	}
}

void List_Print(List* ps)
{

	for (int i = 0; i < ps->size - 1; i++)
	{
		printf("%d ", ps->arr[i]);
	}

}

void List_Destroy(List* ps)
{
	ps->capacity = 0;
	ps->size = 0;
	free(ps->arr);
}